package com.masterclient.app.modules.aftersale.contract;

import android.widget.Toast;

import com.eoner.common.bean.base.CommonBaseBean;
import com.eoner.baselib.presenter.ThrowableConsumer;
import com.eoner.baselibrary.bean.aftersale.ReturnGoodsBean;
import com.eoner.baselibrary.bean.personal.UploadImgBean;
import com.eoner.baselibrary.utils.Utils;
import com.masterclient.app.httpservice.RetrofitUtil;
import com.masterclient.app.httpservice.RetrofitUtil2;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
* Created by TMVPHelper on 2017/08/01
*/
public class ReturnGoodsPresenter extends ReturnGoodsContract.Presenter{

    private String fromType = "";

    public void setFromType(String fromType) {
        this.fromType = fromType;
    }

    @Override
    public void preAfterSale(String refund_type, String order_product_id, String update,String order_id) {

        Disposable disposable = toSubscribe("purchase".equals(fromType)?RetrofitUtil2.getInstance().preAfterSalePurchase(order_id,order_product_id,update)
        :RetrofitUtil.getInstance().preAfterSale(refund_type, order_id,order_product_id, update), new Consumer<ReturnGoodsBean>() {
            @Override
            public void accept(@NonNull ReturnGoodsBean bean) throws Exception {
                if("0".equals(bean.getCode())){
                    mView.preAfterSaleInfo(bean.getData());
                }else {
                    Toast.makeText(Utils.getContext(),bean.getMsg(),Toast.LENGTH_SHORT).show();
                }
            }
        }, new ThrowableConsumer());
        mRxManager.add(disposable);
    }

    @Override
    public void applyAfterSale(String integral, String receive_status, String balance_amount, String bupiao_amount,
                               String description, List<String> images, String order_product_id, String qty, String reason_id,
                               String refund_type, String should_pay_amount, String update, String order_id,
                               String integral_deduction,String address_id,String apply_type,Map<String,String> give_product,
                               String refund_reason_id, String refund_type_id, String refund_shipping) {


            RequestBody body;
            if ("purchase".equals(fromType)){
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("balance_amount",balance_amount);
                    jsonObject.put("bupiao_amount",bupiao_amount);
                    jsonObject.put("description",description);
                    jsonObject.put("order_product_id",order_product_id);
                    jsonObject.put("qty",qty);
                    jsonObject.put("reason_id",reason_id);
                    jsonObject.put("refund_type",refund_type);
                    jsonObject.put("should_pay_amount",should_pay_amount);
                    jsonObject.put("update",update);
                    jsonObject.put("order_id",order_id);
                    jsonObject.put("integral",integral);
                    jsonObject.put("address_id" , address_id);
                    jsonObject.put("receive_status",receive_status);
                    jsonObject.put("integral_deduction",integral_deduction);
                    jsonObject.put("relation_id" , reason_id);
                    jsonObject.put("refund_reason_id" , refund_reason_id);
                    jsonObject.put("refund_type_id" , refund_type_id);
                    if(images!=null && images.size()>0){
                        String imgStr = "";
                        for (String img : images) {
                            imgStr += "," + img;
                        }
                        jsonObject.put("images",imgStr.substring(1));
                    }
                    if (give_product != null){
                        jsonObject.put("give_product",new Gson().toJson(give_product));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), jsonObject.toString());
            }else {
                StringBuilder builder = new StringBuilder();
                builder.append("balance_amount="+balance_amount);
                builder.append("&bupiao_amount="+bupiao_amount);
                builder.append("&description="+description);
                builder.append("&order_product_id="+order_product_id);
                builder.append("&qty="+qty);
                builder.append("&reason_id="+reason_id);
                builder.append("&refund_type="+refund_type);
                builder.append("&should_pay_amount="+should_pay_amount);
                builder.append("&update="+update);
                builder.append("&order_id="+order_id);
                builder.append("&integral="+integral);
                builder.append("&address_id=" + address_id);
                builder.append("&receive_status="+receive_status);
                builder.append("&integral_deduction="+integral_deduction);
                builder.append("&relation_id=" + reason_id);
                builder.append("&refund_reason_id=" + refund_reason_id);
                builder.append("&refund_type_id=" + refund_type_id);
                builder.append("&refund_shipping=" + refund_shipping);
                if(images!=null){
                    for(String img:images){
                        builder.append("&images[]="+img);
                    }
                }
                if (give_product != null){
                    builder.append("&give_product="+new Gson().toJson(give_product));
                }
                body = RequestBody.create(okhttp3.MediaType.parse("application/x-www-form-urlencoded; charset=utf-8"), builder.toString());
            }

            Disposable disposable = toSubscribe("purchase".equals(fromType)? RetrofitUtil2.getInstance().afterSalePurchaseApply(body):RetrofitUtil.getInstance().applyAfterSale(apply_type, body), new Consumer<CommonBaseBean>() {
                @Override
                public void accept(@NonNull CommonBaseBean bean) throws Exception {
                    if("0".equals(bean.getCode())){
                        mView.applyAfterSaleSuccess();
                    }else {
                        mView.showError(bean.getCode(),bean.getMsg());
                    }
                }
            }, new ThrowableConsumer(){
                @Override
                public void accept(Throwable o) throws Exception {
                    super.accept(o);
                    mView.showError("网络异常，请重试");
                }
            });
    }

    @Override
    public void uploadImage(File image, String type, String filename) {


        Map<String, RequestBody> map = new HashMap<>();
        RequestBody requestBody1 =  RequestBody.create(MediaType.parse("multipart/form-data"), image);

        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM);//表单类型

        RequestBody imageBody = RequestBody.create(MediaType.parse("image/png"), image);
        builder.addFormDataPart("imgfile", filename, imageBody);//imgfile 后台接收图片流的参数名
        builder.addFormDataPart("type",type);

        Observable<UploadImgBean> observable = RetrofitUtil.getInstance().uploadImage(builder.build().parts());
        Disposable disposable = toSubscribe(observable, new Consumer<UploadImgBean>() {
            @Override
            public void accept(@NonNull UploadImgBean bean) throws Exception {
                if("0".equals(bean.getCode())){
                    mView.onUploadSuccess(bean.getData());
                }
            }
        }, new ThrowableConsumer());
        mRxManager.add(disposable);
    }
}